# coding=UTF-8
import os
import requests
import time

base_path = os.path.join(os.getcwd().split('StockMonitor')[0] + 'StockMonitor')
from utils import doc_util

# 获取东方财富所有的板块信息
url1 = 'http://quote.eastmoney.com/api/PageConfigs/sidemenus.json'
# 对应板块详情
url2 = 'http://push2.eastmoney.com/api/qt/clist/get?ut=bd1d9ddb04089700cf9c27f6f7426281&pi=0&pz=8&po=1&fid=f62&fs=b:BK0927&=&fields=f1,f2,f12,f13,f14,f62,f152,f128,f3,f62,f184,f66,f69,f72,f75,f78,f81,f84,f87&cb=jQuery1124013032222692515671_1594364218527&_=1594364218723'
url3 = 'http://push2.eastmoney.com/api/qt/clist/get?pn=1&pz=50&po=1&np=1&ut=b2884a393a59ad64002292a3e90d46a5&fltt=2&invt=2&fid=f62&fs=b:BK0713&stat=1&fields=f12,f14,f2,f3,f62,f184,f66,f69,f72,f75,f78,f81,f84,f87,f204,f205,f124&rt=53145555&cb=jQuery18305251896309956461_1594366649033&_=1594366650616'
'''
f2:最新价格
f3:涨跌幅
f12:代码
f14:名称
f62:主力净流入金额
f66:超大单净流入金额
f69:超大订单流入占比
f72:大单净流入金额
f75:大订单流入占比
f78:中单净流入金额
f81:中订单流入占比
f84:小单净流入金额
f87:小订单流入占比

'''


def get_detail_stock(code):
    time_stamp = int(round(time.time() * 1000))
    url_i = 'http://push2.eastmoney.com/api/qt/clist/get?ut=bd1d9ddb04089700cf9c27f6f7426281&pi=0&pz=8&po=1&fid=f62&fs=b:' + code + \
            '&=&fields=f1,f2,f12,f13,f14,f62,f152,f128,f3,f62,f184,f66,f69,f72,f75,f78,f81,f84,f87' \
            '&cb=jQuery1124013032222692515671_' + str(time_stamp) + '&_=' + str(time_stamp + 127)
    resp = requests.get(url_i)
    data = eval(str(resp.content.decode('utf-8')).split('(')[1].split(')')[0].replace('null', '""'))['data']
    total = int(data['total'])
    if total == 0:
        return
    stock_dict = data['diff']
    for rank in stock_dict:
        # 只有8枚
        print(stock_dict[rank])


def get_all_stock_info(code):
    time_stamp = int(round(time.time() * 1000))
    # 获取全部信息
    plate_stock_list = []
    for i in range(1, 100):
        url_ii = 'http://push2.eastmoney.com/api/qt/clist/get?pn=' + str(i) + \
                 '&pz=50&po=1&np=1&ut=b2884a393a59ad64002292a3e90d46a5&fltt=2&invt=2&fid=f62&fs=b:' + code + \
                 '&stat=1&fields=f12,f14,f2,f3,f62,f184,f66,f69,f72,f75,f78,f81,f84,f87,f204,f205,f124&' \
                 'rt=53145555&cb=jQuery18305251896309956461_' + str(time_stamp) + '&_=' + str(time_stamp + 127)
        data_str = ''
        try:
            resp_ii = requests.get(url_ii)
            data_str = str(resp_ii.content.decode('utf-8')).split('(')[1].split(')')[0].replace('null', '""')
        except Exception as e:
            print(url_ii)
            print('Error:', e)
        # finally:
        #     print('')
        data = eval(data_str)['data']
        if data == '':
            break
        total = int(data['total'])
        if total == 0:
            break
        stock_list = data['diff']
        for stock_info in stock_list:
            plate_stock_list.append(stock_info)
        return plate_stock_list


def get_all_paltes_info():
    resp1 = requests.get(url1)
    resp1_content = str(resp1.content.decode('utf-8').replace('true', '1').replace('false', '0'))
    plate_list = eval(resp1_content)
    for plate_one in plate_list:
        print(plate_one)
        title = plate_one['title']
        key = plate_one['key']
        if key == 'hsbroad':
            next = plate_one['next']
            for plate_two in next:
                print(plate_two)
                title_two = plate_two['title']
                key_two = plate_two['key']
                plate_path = os.path.join(base_path, 'common', 'plates', title, title_two)
                doc_util.gen_path(plate_path)
                if str(title_two).__contains__('蚂蚁'):
                    print("##########" + title_two)
                plate_info = {}
                time_tamp = int(round(time.time() * 1000))
                if os.path.exists(os.path.join(plate_path, '板块概况')):
                    plate_general = open(os.path.join(plate_path, '板块概况'), mode='r', encoding='utf-8')
                    plate_info = eval(plate_general.readline()[:-1])
                    if (time_tamp - int(plate_info['up_time'])) > 240 * 3600:
                        plate_general.close()
                        plate_general = open(os.path.join(plate_path, '板块概况'), mode='w', encoding='utf-8')
                    else:
                        continue
                else:
                    plate_general = open(os.path.join(plate_path, '板块概况'), mode='w', encoding='utf-8')
                plate_info['up_time'] = str(int(round(time.time() * 1000)))  # 秒时间戳
                plate_general.write(str(plate_info) + '\n')
                plate_general.write('up_time')
                next_two = plate_two['next']
                for plate_thr in next_two:
                    plate_general.write(str(plate_thr) + '\n')
                    title_thr = plate_thr['title']
                    key_thr = plate_thr['key']
                    path = os.path.join(plate_path, title_thr)
                    if not os.path.exists(path):
                        os.makedirs(path)  # 创建一个文件夹
                    plate_stock_list = get_all_stock_info(key_thr.split('.')[1])
                    plate_file = open(os.path.join(path, key_thr), mode='w', encoding='utf-8')
                    for stock in plate_stock_list:
                        plate_file.write(str(stock) + '\n')
                    plate_file.close()
                plate_general.close()


if __name__ == '__main__':
    print("start")
    get_all_paltes_info()
